package com.rocksea.app.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;

import com.rocksea.app.BaseFragment;
import com.rocksea.app.R;
import com.rocksea.app.activity.BaseShowActivity;
import com.rocksea.app.adapter.FragmentAdapter;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.SonicWave.SonicWave;
import com.rocksea.app.event.UpDateSonicWave;
import com.rocksea.app.interfaces.MyExecuteCallBack;
import com.rocksea.app.tasks.Temp;
import com.rocksea.app.utils.UiUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;


/**
 *
 * @author 吴志华
 * @date 2017/10/26
 * 中间类 容器 放具体3个 6个剖面的fragment
 *
 */

public class SetionInfoFragment extends BaseFragment
{

    @InjectView(R.id.Viewpager)
    ViewPager mViewPager;
    @InjectView(R.id.TabLayout)
    TabLayout mTabLayout;
    private String baseInfoId;

    @OnClick(R.id.Edit)
    public void onKey()
    {
        if (sectionId==null)
        {
            UiUtils.showToast("操作失败(未能找到剖面)");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示");
        builder.setMessage("确定要去除重复的测点数据吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                OneKeyMakeUnValidTask task = new OneKeyMakeUnValidTask(sectionId,getContext(),baseInfoId);
                task.execute();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }


    public static final String SECTION_UUID = "com.rocksea.section.key";
    private int valid;
    private ArrayList<String> sectionId;


    public static SetionInfoFragment newInstance(Bundle bundle)
    {
        SetionInfoFragment fragment = new SetionInfoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void initView()
    {
        loading();
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);

    }

    @Override
    protected void initData()
    {
        Bundle bundle =  getArguments();
        if (bundle!=null)
        {
            baseInfoId = bundle.getString(BaseShowActivity.BASEINFOID_KEY);
            valid = bundle.getInt(SetionViewFragment.VALID_KEY);
            if (Temp.getSonicWave()!=null)
            {
                queryCallBack(Temp.getSonicWave().SonicWaveFaces);
                return;
            }
            loading();
            querySonicWaveSection(baseInfoId, callBack);
        }
    }

    private void querySonicWaveSection(String baseInfoId,MyExecuteCallBack<List<SonicWave.SonicWaveFace>> callBack)
    {
        DbCenter.querySonicWaveSection(baseInfoId,callBack);
    }


    private MyExecuteCallBack<List<SonicWave.SonicWaveFace>> callBack = new MyExecuteCallBack<List<SonicWave.SonicWaveFace>>()
    {
        @Override
        public void onError(int code, String message) {
        }

        @Override
        public void onSuccess(List<SonicWave.SonicWaveFace> sonicWaveFaces)
        {
            handler.obtainMessage(0,sonicWaveFaces);
        }
    };

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 0:
                    queryCallBack((List<SonicWave.SonicWaveFace>) msg.obj);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };

    public void queryCallBack(List<SonicWave.SonicWaveFace> sonicWaveFaces)
    {
        if (sonicWaveFaces.size()==0)
        {
            loadFailed();
        }
        else
        {
            loadCompleted();
            sectionId = new ArrayList<>();
            FragmentAdapter adapter = new FragmentAdapter(getChildFragmentManager());
            String[] titles = new String[sonicWaveFaces.size()];
            List<Fragment> fragments = new ArrayList<>();
            Bundle bundle;
            for (int i = 0; i < sonicWaveFaces.size(); i++)
            {
                StringBuilder builder = new StringBuilder(sonicWaveFaces.get(i).sectionNo);
                builder.insert(1,"-");
                titles[i]=builder.toString();
                bundle = new Bundle();
                bundle.putString(SECTION_UUID,sonicWaveFaces.get(i).sectionId);
                sectionId.add(sonicWaveFaces.get(i).sectionId);
                bundle.putInt(SetionViewFragment.VALID_KEY,valid);
                switch (valid)
                {
                    case -1:
                        fragments.add(SectionInfoAFragment.newInstance(bundle));
                        break;
                    case 0:
                    case 1:
                        fragments.add(SetionViewFragment.newInstance(bundle));
                        break;
                    case 2:
                        fragments.add(DistinctDepthFragment.newInstance(bundle));
                        break;
                }

            }
            adapter.setTitles(titles);
            adapter.setFragments(fragments);
            mTabLayout.setupWithViewPager(mViewPager);
            mViewPager.setAdapter(adapter);

        }
    }


    @Override
    protected void requestAgain() {

    }

    @Override
    protected int getContentViewId()
    {
        return R.layout.fragment_section;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private static class OneKeyMakeUnValidTask extends AsyncTask<Void,Void,Void>
    {
        private ArrayList<String> sectionId;
        private Context context;
        private ProgressDialog mProgressDialog;
        private String baseInfoId;
        public OneKeyMakeUnValidTask(ArrayList<String> sectionId, Context context, String baseInfoId)
        {
            this.sectionId = sectionId;
            this.context = context;
            this.baseInfoId = baseInfoId;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(context,"提示","一键去除重复的测点数据，请稍后...",true,false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            if (DbCenter.mScDbHelper.oneKeyToUnValid(sectionId))
            {
                SonicWave mSonicWave = DbCenter.mScDbHelper.querySonicWaveFragmet(baseInfoId);
                if (mSonicWave!=null)
                {
                    Temp.setSonicWave(mSonicWave); //更新原始数据
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid)
        {
            super.onPostExecute(aVoid);
            mProgressDialog.dismiss();
            EventBus.getDefault().post(new UpDateSonicWave());
            UiUtils.showToast("操作成功");
        }
    }



}
